package com.gxl.butt.service.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.gxl.butt.service.IHardUserService;
import com.gxl.butt.utils.CommonUtil;
import com.gxl.butt.utils.JSONUtils;
import com.gxl.butt.value.StaticValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@CrossOrigin
@RestController
@RequestMapping(value = "/harduser/")
public class HardUserController {



    @Autowired
    private IHardUserService iHardUserService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 判断用户是否登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/isLogin",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject isLogin(HttpServletRequest request) {

        JSONObject userJson = (JSONObject) request.getSession().getAttribute(StaticValue.USER_SESSION);
        if (userJson!=null){
            return JSONUtils.getRoot(0,"has user",null);
        }else {
            return JSONUtils.getRoot(-1,"has no user",null);
        }

    }



    /**
     * 用户注册
     * @param request
     * @param account
     * @param password
     * @param nickname
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject register(HttpServletRequest request, String account, String password, String nickname, String idcard) {



        //大小写字母，数字，特殊字符 全集匹配（只要字符串匹配其中任何一个或多个都可以）
        String reg1="([a-z]){6,8}$";
        Pattern pAll1=Pattern.compile(reg1);
        Matcher mAll1 = pAll1.matcher(account);
        if (account==null||"".equals(account)||!mAll1.matches()){
            return JSONUtils.getRoot(-1,"账号格式错误,6-8位小写字母",null);
        }

        String reg2="([0-9]){6,8}$";
        Pattern pAll2=Pattern.compile(reg2);
        Matcher mAll2 = pAll2.matcher(password);
        if (password==null||"".equals(password)||!mAll2.matches()){
            return JSONUtils.getRoot(-2,"密码格式错误,6-8位数字",null);
        }
        if (nickname==null||"".equals(nickname)||nickname.length()>8){
            return JSONUtils.getRoot(-3,"昵称格式错误,1-8个字符",null);
        }

        if (idcard==null||"".equals(idcard)|| !CommonUtil.isIdNum(idcard)){
            return JSONUtils.getRoot(-5,"证件号格式错误",null);
        }

        JSONObject jsonObject = iHardUserService.registerUser(account, password, nickname,idcard);

        Integer issus = jsonObject.getInteger("error_code");
        String msg = jsonObject.getString("msg");
        if (issus== -1 ){
            return JSONUtils.getRoot(-4,"account has isexiet",null);
        }else if (issus==-2){
            return JSONUtils.getRoot(-6,"idcard has be register",null);
        }

        logger.info("register user info ：" + jsonObject.toJSONString());

        return JSONUtils.getRoot(0,msg,null);
    }

    /**
     * 用户登录
     * @param request
     * @param account
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(HttpServletRequest request, String account, String password) {


        //大小写字母，数字，特殊字符 全集匹配（只要字符串匹配其中任何一个或多个都可以）
        String reg1="([a-z]){6,8}$";
        Pattern pAll1=Pattern.compile(reg1);
        Matcher mAll1 = pAll1.matcher(account);
        if (account==null||"".equals(account)||!mAll1.matches()){
            return JSONUtils.getRoot(-1,"账号格式错误,6-8位小写字母",null);
        }

        String reg2="([0-9]){6,8}$";
        Pattern pAll2=Pattern.compile(reg2);
        Matcher mAll2 = pAll2.matcher(password);
        if (password==null||"".equals(password)||!mAll2.matches()){
            return JSONUtils.getRoot(-2,"密码格式错误,6-8位数字",null);
        }


//        if (account==null||"".equals(account)){
//            return JSONUtils.getRoot(-1,"账号格式错误",null);
//        }

//        if (password==null||"".equals(password)){
//            return JSONUtils.getRoot(-2,"密码格式错误",null);
//        }

        JSONObject jsonObject = iHardUserService.loginUser(account, password);

//        return jsonObject;
        int logincode = jsonObject.getInteger("error_code");
        String msg = jsonObject.getString("msg");
        if (logincode == 0){//登录成功
            JSONObject returndata = new JSONObject();
            returndata.put("account",jsonObject.getJSONObject("data").getString("account"));
            returndata.put("nickname",jsonObject.getJSONObject("data").getString("nickname"));
            returndata.put("idcard",jsonObject.getJSONObject("data").getString("idcard"));
            request.getSession().setAttribute(StaticValue.USER_SESSION,jsonObject.get("data"));
            request.getSession().setMaxInactiveInterval(48*60*60);
            logger.info("login user info ：" + returndata);
            return JSONUtils.getRoot(0,msg,returndata);
        } else{
             logger.info("登录失败:" + msg);
            return JSONUtils.getRoot(-3,msg,null);
        }

    }

    /**
     * 用户登出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject logout(HttpServletRequest request) {

//        if (!CheckControllerIsLogin.isLogin(request)){
//            return  JSONUtils.getRoot(-10000,"用户未登录",null);
//        }
//        request.getSession().invalidate();//注销整个session的所有信息
        request.getSession().removeAttribute(StaticValue.USER_SESSION);//注销指定key为HARD_USER的信息
        return JSONUtils.getRoot(0,"user was logout",null);

    }


    /**
     * 查询用户账号是否被注册
     * @param request
     * @param account
     * @return
     */
    @RequestMapping(value = "/checkAccount",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject checkAccount(HttpServletRequest request, String account) {

        //大小写字母，数字，特殊字符 全集匹配（只要字符串匹配其中任何一个或多个都可以）
        String reg1="([a-z]){6,8}$";
        Pattern pAll1=Pattern.compile(reg1);
        Matcher mAll1 = pAll1.matcher(account);
        if (account==null||"".equals(account)||!mAll1.matches()){
            return JSONUtils.getRoot(-1,"账号格式错误,6-8位小写字母",null);
        }

//        if (account==null||"".equals(account)){
//            return JSONUtils.getRoot(-1,"账号格式错误",null);
//        }

        JSONObject jsonObject = iHardUserService.checkAccount(account);

        int logincode = jsonObject.getInteger("error_code");
        String msg = jsonObject.getString("msg");
        if (logincode == 0){//账号可用
            return JSONUtils.getRoot(0,msg,null);
        } else{
            return JSONUtils.getRoot(-2,msg,null);
        }

    }


}
